import * as request from 'request';

export interface HuoShanVideo {
  cover: string, // 封面图
  url: string, // 无水印视频地址
}

/**
 * 正则分享字符串解析出地址
 * @param share 
 */
function parseShareStr(share: string): string {
  const reg = /(?:(https?|ftp|file):)?\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g; // 匹配 https://  ftp://  file://  这样开头的链接

  const shortUrls = share.match(reg);
  if (null == shortUrls) {
    console.log(` _parseShareStr fail, douYin = [${share}]`);
    return '';
  }
  else if (!shortUrls[0]) {
    console.log(` _parseShareStr no data, douYin = [${share}]`);
    return '';
  }
  console.log(' _parseShareStr result = ', shortUrls);
  return shortUrls[0];
}

/**
 * 解析火山视频的分享链接获得下载地址
 * 例如: 1、楚天交通广播在火山分享了视频，快来围观！传送门戳我>>https://share.huoshan.com/hotsoon/s/1X25cJZNqi8/ 复制此链接，打开【火山极速版】，直接观看视频~
 *  2、东南军情在火山分享了视频，快来围观！传送门戳我>>https://share.huoshan.com/hotsoon/s/3V3yYe1Oqi8/ 复制此链接，打开【抖音火山版】，直接观看视频~  
 * @param shareTestStr 
 */
async function huoShan(shareTestStr: string): Promise<null | HuoShanVideo> {
  return new Promise((resolve, reject) => {
    const headers = {
      'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Mobile Safari/537.36',
    };
    const shareUrl = parseShareStr(shareTestStr);
    request.get(shareUrl, { headers: headers }, (err: any, res: request.Response) => {
      if (err) {
        console.error(` _getShareUrl err = ${err}`);
        return resolve(null);
      }
      const href = res.request.uri.href;
      if (!href) {
        console.error(' _getShareUrl not have href ');
        return resolve(null);
      }

      const regItemId = /item_id=[0-9]+[0-9]/g; // 匹配 item_id=6963880784470068491 
      const itemIds = href.match(regItemId);
      if (!itemIds || !itemIds[0]) {
        console.error(' get itemid fail ');
        return resolve(null);
      }
      const itemId = itemIds[0].replace('item_id=', '');
      console.log(' itemId = ', itemId);

      // 根据 itemId 去获得有水印的播放地址
      const videoUrl = `https://share.huoshan.com/api/item/info?item_id=${itemId}`;
      request.get(videoUrl, { headers: headers }, (err: any, res: request.Response) => {
        if (err) {
          console.error(` _getVideoUrl err = ${err}`);
          return resolve(null);
        }

        interface VideoUrlResType {
          status_code: number,
          data: {
            item_info: {
              item_id: string,
              cover: string, // 封面图
              url: string, // 有水印的播放地址
            },
          },
        }
        let data: VideoUrlResType;
        try {
          data = JSON.parse(res.body);
        }
        catch (err) {
          console.error(' _parse fail, err = ', err);
          return resolve(null);
        }
        if (data.status_code != 0) {
          console.error(' _getVideoUrl fail, status_code = ', data.status_code);
          return resolve(null);
        }
        // console.log(' origin url = ', data.data.item_info.url);

        const regVideoId = /video_id=(.*)&line/g; // 匹配 video_id=v0300fg10000c2iapbb6v4nagaol79v0&line
        const videoIds = data.data.item_info.url.match(regVideoId);
        if (!videoIds || !videoIds[0]) {
          console.error(' get videoId fail ');
          return resolve(null);
        }
        const videoId = videoIds[0].replace('video_id=', '').replace('&line', '');
        console.log(' videoId = ', videoId);

        const result: HuoShanVideo = {
          cover: data.data.item_info.cover,
          url: `https://api-hl.huoshan.com/hotsoon/item/video/_playback/?video_id=${videoId}`,
        };
        return resolve(result);
      });
    });
  });
}

async function main() {
  const share = '楚天交通广播在火山分享了视频，快来围观！传送门戳我>>https://share.huoshan.com/hotsoon/s/1X25cJZNqi8/ 复制此链接，打开【火山极速版】，直接观看视频~';
  // const share = '东南军情在火山分享了视频，快来围观！传送门戳我>>https://share.huoshan.com/hotsoon/s/3V3yYe1Oqi8/ 复制此链接，打开【抖音火山版】，直接观看视频~  ';
  const result = await huoShan(share);
  if (!result) {
    console.error(' --- fail ---');
    return;
  }
  console.log(' --- success ---');
  console.log(result);
}
main();